﻿/**
 * @fileoverview Giant Interective Group, Inc. Javascript Library v#version.
 * 该Javascript UI库是基于jQuery的扩展。
 * <pre>
 * Copyright (C) 2004-2009 Giant Interective Group, Inc. All rights reserved.
 * 版权所有 2004-2009 上海巨人网络科技有限公司
 * </pre>
 *
 * @version #version, #date
 * @author  Zhangkai
 * Depend on jQuery 1.3.x
 */
if(typeof giant === 'undefined')
    var giant = window.giant = {};
if(typeof giant.ui === 'undefined')
    giant.ui = {};
(function($) {
	/**
     * 创建一个新的好友屏蔽器控件。
     * @class giant.ui.friendblock。Giant UI 的friendblock控件。
     * @example 
     * <pre>
     *   &lt;div id=&quot;ui-fb&quot; class=&quot;ui-fb&quot;&gt;
     *      &lt;div class=&quot;ui-fb-userresult clearfix&quot;&gt;
     *      &lt;/div&gt;
     *      &lt;div class=&quot;ui-fb-groupresult clearfix&quot;&gt;
     *      &lt;/div&gt;
     *      &lt;div class=&quot;ui-fb-input&quot;&gt;
     *         &lt;input type=&quot;text&quot; value=&quot;输入好友姓名(支持全拼输入)&quot; maxlength=&quot;30&quot; /&gt;
     *         &lt;a class=&quot;ui-fb-icon&quot; href=&quot;javascript:void(0)&quot; title=&quot;选择好友分组&quot;&gt;选择好友分组&lt;/a&gt;
     *   &lt;/div&gt;
     *      &lt;div class=&quot;ui-fb-list&quot;&gt;
     *       数据加载中....
     *      &lt;/div&gt;
     *      &lt;div class=&quot;ui-fb-group&quot;&gt;
     *      &lt;/div&gt;
     *  &lt;/div&gt;
     *  $(document).ready(function(){
     *      var test = new giant.ui.friendblock({
     *          ajaxUrl:"test.asp"
     *      });
     *  });
     * </pre>
     */
    giant.ui.friendblock = function(options) {
        this.opts = $.extend({}, giant.ui.friendblock.defaults, options);
        this.userResultArr = [];
        this.groupResultArr = [];
        this.isGroupListShow = false;   //是否已经显示组列表
        this.isUserListShow = false; //是否已经显示好友列表
        this.activeIndex=0;
        this._init();
    };
    giant.ui.friendblock.prototype = {
        _init:function(){
            this._clickBind();
            this._focusBind();
            this._blurBind();
            this._keyUpBind();
        },
        _clickBind:function() {
            var $this = this;
            //右侧查看组小图标
            $($this.opts.btnGroup).bind("click", function() {
                if($this.isGroupListShow){
                     $this.setGroupListHide();
                }else{
                   $this.setGroupListShow();
                   $this._getData("组",function(msg){
                         if (msg.length > 0) {
                                var data = eval(msg);
                                var arr = [];
                                arr.push("<ul>")
                                $.each(data, function(i, n) {
                                    if(i==0){
                                    arr.push(" <li class='active' name='"+n.gid+"'><h4>"+n.name+"</h4><p>"+n.description+"</p></li>");
                                    }else{
                                      arr.push(" <li name='"+n.gid+"'><h4>"+n.name+"</h4><p>"+n.description+"</p></li>");  
                                    }
                                });
                                arr.push("</ul>")
                                $($this.opts.groupListContainer).html(arr.join(''));
                                $($this.opts.groupListContainer).find("li").each(function(index){
                                   $(this).bind("mouseover",function(){
                                     $this.activeIndex = index;
                                     $($this.opts.groupListContainer).find("li").removeClass("active");
                                     $($this.opts.groupListContainer).find("li").eq($this.activeIndex).addClass("active");
                                   });
                                  $(this).bind("click",function(){
                                    $this.addGroup($(this).attr("name"),  $(this).find("h4").text());
                                    $this.setUserListHide();
                                   });  
                               });
                            } else {
                                $($this.opts.groupListContainer).html($this.opts.noDataTip);
                            }
                   });
                }
            });
            //点击删除好友
            $($this.opts.userResultContainer).find("span").live("click", function() {
                $this.deleteUser($(this).parents("a"));
            });
             $($this.opts.groupResultContainer).find("span").live("click", function() {
                $this.deleteGroup($(this).parents("a"));
            });
        },
        _focusBind:function() {
            var $this = this;
            $($this.opts.input).bind("focus", function() {
                $(this).val("");
                $this.setGroupListHide();
                $($this.opts.inputContainer).css("border-color","#7f9db9");
            });
        },
        _blurBind:function() {
            var $this = this;
            $($this.opts.input).bind("blur", function() {
                $($this.opts.inputContainer).css("border-color","#999");
                setTimeout(function(){$this.setUserListHide();},200);
            });
        },
        _keyUpBind:function() {
            var $this = this;
            $(this.opts.input).bind("keyup", function(event) {
                if (event.keyCode != "40" && event.keyCode != "38" && event.keyCode != "39" && event.keyCode != "37"&& event.keyCode != "13") {
                    if ($($this.opts.input).val().length > 0) {
                       $this.setUserListShow();
                        $this._getData($(this).val(), function(msg) {
                            if (msg.length > 0) {
                                var data = eval(msg);
                                var arr = [];
                                arr.push()
                                $.each(data, function(i, n) {
                                    arr.push("<a href='javascript:void(0)' title='" + n.name + "' name='" + n.uid + "'><img src='http://www.playgoogle.com/demo/friendsuggest/" + n.image + "' title='" + n.uid + "' alt='' />" + n.name + "</a>");
                                });
                                $($this.opts.userListContainer).html(arr.join(''));
                            } else {
                                $($this.opts.userListContainer).html($this.opts.noDataTip);
                            }
                            $($this.opts.userListContainer).find("a").eq(0).addClass("active");
                            $($this.opts.userListContainer).find("a").each(function(index) {
                                $(this).bind("mouseover", function() {
                                    $this.activeIndex = index;
                                    $($this.opts.userListContainer).find("a").removeClass("active");
                                    $($this.opts.userListContainer).find("a").eq($this.activeIndex).addClass("active");
                                });
                                $(this).bind("click", function() {
                                    var $obj = $($this.opts.userListContainer).find("a.active");
                                    $this.addUser($obj.attr("name"), $obj.text(), $obj.find("img").attr("src"));
                                    $this.setUserListHide();
                                    $($this.opts.input).focus();
                                });
                           });
                        });
                    }
                    else {       //输入为空
                        $($this.opts.userListContainer).html($this.opts.inputDefaultTip);
                    }
                }
                if ($this.isUserListShow) {
                    var totalCount = $($this.opts.userListContainer).find("a").size();
                    if (totalCount > 0) {
                        //down 键
                        switch (event.keyCode) {
                            case 40:
                                if ($this.activeIndex < totalCount - 1) $this.activeIndex++;
                                else  $this.activeIndex = 0;
                                break;
                            case 38:
                                if ($this.activeIndex > 0)  $this.activeIndex--;
                                else  $this.activeIndex = totalCount - 1;
                                break;
                            case 13:
                                var $obj = $($this.opts.userListContainer).find("a.active");
                                $this.addUser($obj.attr("name"), $obj.text(), $obj.find("img").attr("src"));
                                $this.setUserListHide();
                                break;
                            default:
                                $($this.opts.userListContainer).find("a").removeClass("active");
                                $($this.opts.userListContainer).find("a").eq($this.activeIndex).addClass("active");
                                break;
                        }
                    }
                }
            });
        },
        _getData:function(type,callBack) {         //全部friend 列表
            var $this = this;
             if ($this.xmlHttpObj) {
                $this.xmlHttpObj.abort();
                $this.xmlHttpObj = null;
            }
            $this.xmlHttpObj =$.ajax({
                url:$this.opts.ajaxUrl,
                data:"name=" + type,
                before:function(){
                   if ($.isFunction($this.opts.ajaxBefore)) {
                        $this.opts.ajaxBefore.call($this);
                    } 
                },
                success:function(msg) {
                    if ($.isFunction(callBack)) {
                        callBack(msg);
                    }
                },
                error:function(){
                     if ($.isFunction($this.opts.ajaxError)) {
                        $this.opts.ajaxError.call($this);
                    } 
                }
            });
        },
        /**
         *添加用户
         * @param{string} uid 用户id 
         * @param{string} name 用户名字
         * @param{string} image 用户图片
         */
        addUser:function(uid, name, image) {
            var $this = this;
            //如果当前用户不存在
            if ($.inArray(uid, $this.userResultArr) == -1) {
                $this.userResultArr.push(uid);
                $($this.opts.userResultContainer).append("<a href='javascript:void(0)' name='" + uid + "'><img src='" + image + "' title='" + uid + "' alt='' />" + name + "<span title='移除'>移除</span></a>")
            } else {
                var $obj = $($this.opts.userResultContainer).find("[name='" + uid + "']");
                $this._colorFlash($obj);
            }
        },
        /**
         *添加组
         * @param{string} gid 组id 
         * @param{string} name 组名字
         */
        addGroup:function(gid,name){
            var $this = this;
           if ($.inArray(gid, $this.groupResultArr) == -1) {
                $this.groupResultArr.push(gid);
                $($this.opts.groupResultContainer).append("<a href='javascript:void(0)' name='" + gid + "'>" + name + "<span title='移除'>移除</span></a>")
            } else {
                var $obj = $($this.opts.groupResultContainer).find("[name='" + gid + "']");
               this._colorFlash($obj);
            }
        },
        /**
         *删除用户
         * @param{Jquery} $obj 用户id 
         */
        deleteUser:function($obj) {
            var $this = this;
            $this.userResultArr = [];
            $obj.siblings("a").each(function() {
                $this.userResultArr.push($(this).attr("name"));
            });
            $obj.remove();
        },
        /**
         *删除组
         * @param{Jquery} $obj 组id 
         */
        deleteGroup:function($obj) {
            var $this = this;
            $this.groupResultArr = [];
            $obj.siblings("a").each(function() {
                $this.groupResultArr.push($(this).attr("name"));
            });
            $obj.remove();
        },
        /**
         *显示下拉提示
         */
        setUserListShow:function() {
            this.isUserListShow = true;
            this.setGroupListHide();
            $(this.opts.userListContainer).show();
        },
         /**
         *隐藏下拉提示
         */
         setUserListHide:function() {
            this.isUserListShow = false;
            this.activeIndex = 0;
            $(this.opts.userListContainer).hide();
            $(this.opts.input).val("");
            $(this.opts.userListContainer).html("");
        },
        /**
         *显示组
         */
        setGroupListShow:function(){
            this.isGroupListShow = true;
            $(this.opts.groupListContainer).show();
            this.setUserListHide();
        },
        /**
         *隐藏组
         */
        setGroupListHide:function(){
            this.isGroupListShow = false;
            $(this.opts.groupListContainer).hide();
        },
        /**
         *获取选中的好友结果
         *@return{object} 存放选中的好友数组和好友组数组  
         */
        getResult:function() {
            var result = {};
            result.user =this.userResultArr;
            result.group=this.groupResultArr;
            return result;
        },
        _colorFlash:function($obj){
              var i = 0;
              $obj.css("background-color", "#fff");
                //变色
                var interval = setInterval(function() {
                    //IE和FF颜色输出不一样
                    if ($obj.css("background-color") == "#ffffff"||$obj.css("background-color")=="rgb(255, 255, 255)") {
                        $obj.css("background-color", "#6699cc");
                        $obj.css("color", "#fff");
                    } else {
                        $obj.css("background-color", "#ffffff");
                        $obj.css("color", "#666666");
                    }
                    i++;
                    if (i == 4) {
                        $obj.attr("style","");
                        $obj.css("color", "#0099CC");
                        clearInterval(interval);
                    }
                }, 300);
        }
    }
     /**
     *默认参数
     *@default
     * <pre>
     * btnGroup==>  打开组选择的按钮
     * userResultContainer==> 好友列表容器
     * groupResultContainer==> 组列表容器
     * input==>  输入框
     * userListContainer==> 好友列表容器
     * groupListContainer ==> 好有组列表
     * inputDefaultTip==>默认提示
     * noDataTip ==>无数据提示
     * </pre>
     */
    giant.ui.friendblock.defaults = {
        btnGroup:"#ui-fb .ui-fb-input .ui-fb-icon",
        userResultContainer:"#ui-fb .ui-fb-userresult",
        groupResultContainer:"#ui-fb .ui-fb-groupresult",
        input:"#ui-fb .ui-fb-input input",
        userListContainer:"#ui-fb .ui-fb-list",
        groupListContainer:"#ui-fb .ui-fb-group",
        inputDefaultTip:"输入好友姓名(支持全拼输入)",
        noDataTip:"姓名不在好友列表中,请重新输入",
        ajaxUrl:"test.asp",
        ajaxBefore:null,
        ajaxError:null
    };
})(jQuery);
